package com.seanliao.nav.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.seanliao.nav.common.exception.BusinessException;
import com.seanliao.nav.common.response.Result;
import com.seanliao.nav.common.response.ResultBuilder;
import com.seanliao.nav.entity.SysUser;
import com.seanliao.nav.security.MyUserDetails;
import com.seanliao.nav.service.ISysUserService;
import com.seanliao.nav.util.PasswordUtil;
import com.seanliao.nav.util.SecurityUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户个人设置
 */
@Slf4j
@RestController
@RequestMapping("/setting")
@RequiredArgsConstructor
public class SettingController {

    private final ISysUserService sysUserService;

    /**
     * 修改密码
     */
    @PostMapping("/password")
    @PreAuthorize("@pms.hasPermission('setting:password')")
    public Result<?> editPassword(HttpServletRequest request,
                                  HttpServletResponse response,
                                  @RequestParam String oldPassword,
                                  @RequestParam String newPassword
    ) {
        MyUserDetails myUserDetails = SecurityUtil.getCurrentUser();
        // 检查旧密码
        Assert.isTrue(PasswordUtil.match(oldPassword, myUserDetails.getPassword()),
                () -> new BusinessException("密码错误"));
        // 检查新密码
        Assert.isTrue(StrUtil.isNotBlank(newPassword), () -> new BusinessException("必须填写新密码"));
        Assert.isFalse(PasswordUtil.match(newPassword, myUserDetails.getPassword()), () -> new BusinessException("新密码不可与旧密码相同"));
        int length = StrUtil.length(newPassword);
        Assert.isTrue(length > 6 && length <= 16, () -> new BusinessException("新密码长度异常"));
        // 更新实体
        SysUser sysUser = new SysUser();
        sysUser.setId(myUserDetails.getUserId());
        sysUser.setPassword(PasswordUtil.encode(newPassword));
        // 入库
        if (sysUserService.updateById(sysUser)) {
            // 需重新登录
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            new SecurityContextLogoutHandler().logout(request, response, authentication);
            return ResultBuilder.success();
        } else {
            return ResultBuilder.fail("数据写库失败");
        }
    }


}
